<?php

// Prevent individual file access
if(!defined('DIR_BASE')) exit;

/**
 * Controlling a table
 */
class Table{
	
	/**
	 * Tablename
	 */
	private $tablename;
	
	/**
	 * Primary key in the table with auto-increment
	 */
	private $pk;
	
	/**
	 * All the columns that must by modified in the table
	 */
	private $columns = array();
	
	/**
	 * Initialize the interaction with the table
	 * @param String $tablename The tablename
	 * @pram Array $columns Contains an array of columns to interact with
	 */
	public function __construct($tablename, $columns){
		$this->tablename = $tablename; 
		$first = true;
		if(!is_array($columns)){
			$columns = func_get_args();
			array_shift($columns);
		}
		foreach($columns as $column){
			$this->columns[$column] = '';
			if($first)
				$this->pk = $column;
			$first = false;
		}
	}
	
	/**
	 * Get a row in the table through the primary key
	 * @param String $value The value of the pk
	 * @return Array Row with data
	 */
	public function get($value){
		$qb = new QueryBuilder();
		$qry = $qb	-> select()
					-> table($this->tablename)
					-> where($this->pk.' = '.$value)
					-> build();
		return Database::query($qry);
	}
	
	/**
	 * Insert/update a record
	 * $param Array $values An associative array, depending on a given pk 
							to decide if it has to be inserted or updated
							array(
								'id' => 4,
								'column' => 'Update this where id = 4'
							)
	 */
	public function store($values = array()){
		
		if(empty($values)){
			foreach($values as $key => $value){
				if(!isset($this->columns[$key]))
					unset($unset[$key]);
			}
		}
		$id = 0;
		$qb = new QueryBuilder();
		if(isset($values[$this->pk])){
			unset($values[$this->pk]);
			$qry = $qb	-> update()
						-> table($this->tablename)
						-> set($values)
						-> where($this->pk, $values[$this->pk])
						-> build();
			Database::query($qry);
		}else{
			$qry = $qb	-> insert()
						-> table($this->tablename)
						-> set($values)
						-> build();
			Database::query($qry);
			$id = mysql_insert_id();
		}
		return $id;
	}
	
	/**
	 * Delete a record
	 * @param String value Key value
	 */
	public function delete($value){
		$qb = new QueryBuilder();
		$qry = $qb	-> delete()
					-> table($this->tablename)
					-> where($this->pk, $value)
					-> build();
		return Database::query($qry);
	}
}

?>